package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {
    //根据ID查询商品详情
    @Override
    public SpuDetailDTO listSpuDetailById(Long id) {

        SpuDetail spuDetail = this.getById(id);

        return  new SpuDetailDTO(spuDetail);
    }
    @Autowired
    private SpecParamService specParamService;
    @Autowired
    private SpuService spuService;
    @Autowired
    private SpuDetailService spuDetailService;
    //TODO 根据spuId查询spu的所有规格参数值(SpecParam)
    @Override
    public List<SpecParamDTO> listSpecParamBySpuId(Long pid, Boolean searching) {
        //根据商品id查询对应的spu
        Spu spu = this.spuService.getById(pid);

        if (null==spu){
            throw new LyException(204,"此商品不存在");
        }
        //1.查询规格参数，
        List<SpecParamDTO> specParamDTOS = this.specParamService.listSpecParam(null, spu.getCid3(), searching);

        //判断查询条件下的规格参数是否存在
        if (CollectionUtils.isEmpty(specParamDTOS)){
            throw new LyException(500,"商品对应的规格参数不存在");
        }
        //2,查询规格参数对应的属性值
        SpuDetail spuDetail = this.spuDetailService.getById(pid);

        if (null==spuDetail){
            throw new LyException(500,"对应的商品详情不存在");
        }
        //TODO json字符串，1，java，map，2，js，对象,map的key，就是规格参数的id，就是specParamDTO.getId(),value就是对应的规格参数的值
        Map<Long,Object> specParamMap =
                JsonUtils.nativeRead(spuDetail.getSpecification(),
                        new TypeReference<Map<Long,Object>>() {
                        }) ;
        //3，适配规格参数以及属性值
        specParamDTOS.forEach(specParamDTO -> specParamDTO.setValue(specParamMap.get(specParamDTO.getId())));
        return specParamDTOS;
    }
}
